package ma.ensao.evalmetrics.controller;

import java.util.List;

import ma.ensao.evalmetrics.model.Stat;
import ma.ensao.evalmetrics.util.HibernateUtil;

import org.hibernate.classic.Session;
/*
* Recuperation des statistiques de test d'un projet 
*/
public class StatManager extends HibernateUtil {
	public Stat add(Stat stat) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(stat);
		session.getTransaction().commit();
		return stat;
	}

	public List<Stat> MesStats(Long id) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		List<Stat> stat = (List<Stat>) session.createQuery("from Stat where idProjet=" + id + "").list();

		session.getTransaction().commit();

		return stat;
	}
	
	public Stat LastStat(Long id) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Stat stat = (Stat) session.createQuery(
				"from Stat where idProjet=" + id + " AND date IN (SELECT max(date) FROM Stat where idProjet=" + id+")").uniqueResult();

		session.getTransaction().commit();

		return stat;
	}
	
	public Stat beforeLast(Long id) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Stat stat = (Stat) session.createQuery(
				"from Stat where idProjet="+id+" AND date IN (SELECT MAX( date ) FROM Stat WHERE idProjet="+id+" AND date < ( SELECT MAX(date) FROM Stat where idProjet="+id+"))").uniqueResult();

		session.getTransaction().commit();

		return stat;
	}
}